#ifndef _LOGIC_H_
#define _LOGIC_H_

#include <iostream>
#include <map>
#include "netserver.h"
#include "netclient.h"
#include "mpool.h"
#include "bs_def.h"
#include "db_interface.h"
#include "log.h"
#include "config.h"

#define LOGIC_DEF_OVERTIME      60

class WAMessage{
    public:
        WAMessage(){
            fd = -1;
            buf = NULL;
        }
        WAMessage(int fd, char* buf, int size){
            this->fd = fd;
            this->buf = new char[size+1];
            strncpy(this->buf, buf, size);
            this->buf[size] = 0;
        }
        ~WAMessage(){
            delete buf;
        }

        int                 fd;
        char*               buf;
};

class LogicServer{
    public:
        LogicServer(const char* conf);

        /*
        LogicServer(int port):m_config("conf/main.conf"),log("log/server"),m_db("127.0.0.1", 0),m_server(port){
            m_overtime = LOGIC_DEF_OVERTIME;
            m_is_server = true;
            m_is_client = false;
        }

        LogicServer(const char* dataip, int dataport, int port):m_config("conf/main.conf"),log("log/server"),m_db(dataip, dataport),m_server(port){
            m_overtime = LOGIC_DEF_OVERTIME;
            m_is_server = true;
            m_is_client = false;
        }
        */

        /**
         * 主执行函数
         */
        void run();
        /**
         * 主处理函数
         * fd: http端socket
         */
        virtual void main_handle(MongoClient& client, const WAMessage* msg) = 0;

        void main_run();
        void recv_run();

        inline const char* getDBServerIp(){
            return m_config.getString("DBSERVER_IP");
        }
        inline int getDBServerPort(){
            return m_config.getInt("DBSERVER_PORT");
        }
        inline bool isConnectServer(){
            return m_client.isConnected();
        }
        inline void connectServer(){ 
            m_client.Connect(m_config.getString("DBSERVER_IP"), m_config.getInt("DBSERVER_PORT"));
        }
        inline int getOvertime(){
            return m_overtime;
        }
        inline Log& getLog(){
            return log;
        }

        const static int STREAM_BUF_SIZE = 1024000;
    protected:
        // 本程序为server端时的超时时间
        int             m_overtime;
        // 与web端的连接是否为长连接
        bool            m_conn_is_long;

        Config          m_config;
        NetServer       m_server; //该Logic为server
        NetClient       m_client; //该logic为client，相对与dbserver
        Log             log;
        MPool<WAMessage*> m_msg_pool;

        const char*     m_version;
        bool            m_is_server;
        bool            m_is_client;
};

#endif
